import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@PostMapping("/admin/upload")
    public ResultUtils singleFileUpload(@RequestParam("file") MultipartFile file) throws UnsupportedEncodingException {
        System.out.println("python run");
        String rootDir = request.getSession().getServletContext().getRealPath("/");
        //要保存的目录路径
        String filepath = rootDir + File.separator + "tempfile";
        File saveDir = new File(filepath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();// 如果文件夹不存在则创建文件夹
        }
        //文件路径
        filepath = filepath + File.separator + file.getOriginalFilename();
        File tempFile = new File(filepath);   //获取临时文件的位置
        if (file.isEmpty()) {
            return ResultUtils.newFail("请选择一个文件进行上传", StatusCodeUtils.DATAERROR);
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filepath);
            Files.write(path, bytes);
            String pythonPath = "/insertData8.2.py";
            System.out.println();

            String[] cmdPython = new String[3];
            cmdPython[0] = "python3";
            cmdPython[1] = pythonPath;
            cmdPython[2] = path.toString();

            // 调用Python脚本处理上传的文件

            Process process = Runtime.getRuntime().exec(cmdPython);

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Python: " + line);
            }

            reader.close();

            // 读取标准错误输出（可选）
            String errorInformation;
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((errorInformation = errorReader.readLine()) != null) {
                System.err.println(errorInformation);
            }
            // 关闭错误读取器
            errorReader.close();

            // 等待命令执行完毕
            int exitCode = process.waitFor();
            System.out.println("Python脚本执行完毕，退出码: " + exitCode);
            System.out.println("path:" + path);


            if (tempFile.exists()) {
                tempFile.delete();
            }
            return ResultUtils.newSuccess(null);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return ResultUtils.newFail("数据导入失败"+e.getMessage(), StatusCodeUtils.OPERATIONFAILED);
        }
    }